from flask import current_app
from flask import g, jsonify
from flask import request

from info import constants
from info import db
from info.models import Category, News
from info.modules.profiles import profiles_blue
from flask import render_template,redirect

from info.utils.commons import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET


@profiles_blue.route('/info')
@user_login_data
def user_info():
    if not g.user:
        return redirect('/')
    dict_data={
        'user_info' : g.user.to_dict()
    }


    return render_template('news/user.html',dict_data = dict_data)

@profiles_blue.route('/base_info' ,methods=['GET','POST'])
@user_login_data
def base_info():
    if request.method == 'GET':
        dict_data = {
            'user_info' : g.user.to_dict()
        }

        return render_template('news/user_base_info.html' , dict_data = dict_data)

    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if not gender in ['MAN','WOMAN']:
        return jsonify(errno=RET.DATAERR,errmsg='没有此性别')

    g.user.nick_name = nick_name
    g.user.signature = signature
    g.user.gender = gender

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK,errmsg='操作成功')

@profiles_blue.route('/pic_info' , methods=['GET','POST'])
@user_login_data
def pic_info():

    if request.method == 'GET':

        dict_data ={
            'user_info' : g.user.to_dict()
        }
        return render_template('news/user_pic_info.html' , dict_data = dict_data)

    avatar = request.files.get('avatar')

    if not avatar:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    try:
        image_name =  image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云异常")

    if not image_name:
        return jsonify(errno=RET.NODATA,errmsg="图片上传失败")

    g.user.avatar_url = image_name

    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name

    return jsonify(errno=RET.OK,errmsg="上传成功",dict_data={"avatar_url":avatar_url})

@profiles_blue.route('/pass_info' , methods=['GET','POST'])
@user_login_data
def pass_info():

    if request.method == 'GET':

        dict_data ={
            'user_info' : g.user.to_dict()
        }
        return render_template('news/user_pass_info.html' , dict_data = dict_data)

    old_pwd = request.json.get('old_password')
    new_pwd = request.json.get('new_password')
    new_pwd2 = request.json.get('new_password2')

    if not all([old_pwd,new_pwd,new_pwd2]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if new_pwd !=new_pwd2:
        return jsonify(errno=RET.PARAMERR,errmsg='两次密码不想通风')

    g.user.password = new_pwd
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='修改密码失败')

    return jsonify(errno=RET.OK,errmsg='success')

@profiles_blue.route('/collection')
@user_login_data
def collection():

    page = request.args.get("page", "1")

    try:
        page = int(page)
    except Exception as e:
        page = 1

    try:
        paginate = g.user.collection_news.paginate(page, 4, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    dict_data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_list
    }

    return render_template('news/user_collection.html' , dict_data = dict_data)

@profiles_blue.route('/news_release',methods=['GET','POST'])
@user_login_data
def news_relesase():

    if request.method == 'GET':

        try:
            category = Category.query.all()
        except Exception as e :
            current_app.logger.error(e)
            return jsonify(errno=RET.NODATA,errmsg='查询失败')

        return render_template('news/user_news_release.html' , category = category)

    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')

    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errn0=RET.PARAMERR,errmsg='参数不全')

    try:
        image_name = image_storage(index_image.read())
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传图片失败')

    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")

    return jsonify(errno=RET.OK, errmsg="success")

@profiles_blue.route('/news_list')
@user_login_data
def news_list():

    page = request.args.get("page", "1")

    try:
        page = int(page)
    except Exception as e:
        page = 1

    try:
        paginate = News.query.filter(News.user_id==g.user.id).order_by(News.create_time.desc()).paginate(page,10,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())

    dict_data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_list
    }

    return render_template('news/user_news_list.html' , dict_data = dict_data)

@profiles_blue.route('/user_follow')
@user_login_data
def user_follow():

    page = request.args.get("page", "1")

    try:
        page = int(page)
    except Exception as e:
        page = 1

    try:
        paginate = g.user.followed.paginate(page, 4, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户失败")

    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    author_list = []
    for author in items:
        author_list.append(author.to_dict())

    dict_data = {
        "total_page": total_page,
        "current_page": current_page,
        "author_list": author_list
    }

    return render_template('news/user_follow.html' , dict_data = dict_data)

